<template>
  <VanField
    class="money-field"
    :class="cssClass"
    :style="cssStyle"
    :model-value="modelValue"
    @update:modelValue="onUpdate"
    type="number"
    label="¥"
    label-width="auto"
    :formatter="formatter"
    @blur="onBlur"
  />
</template>

<script setup>
import { nextTick, computed } from "vue";
import { normaliseCssSize, getSizeClass } from "../utils/cssUtils";

const props = defineProps({
  modelValue: [String, Number],
  size: String,
});
const emit = defineEmits(["update:modelValue"]);

let cssClass = computed(() => {
  return getSizeClass(props.size, "money-field--");
});

let cssStyle = computed(() => {
  return normaliseCssSize(props.size, "font-size");
});

const formatter = (value) => {
  if (value[0] === ".") {
    value = `0${value}`;
  }
  if (/^0+[1-9]/.test(value)) {
    value = value.replace(/^0+/g, "");
  }

  if (/\.[0-9]{2,}$/g.test(value)) {
    let parts = value.split(".");
    value = parts[0] + "." + parts[1].substring(0, 2);
  }

  return value;
};

const onUpdate = (value) => {
  emit("update:modelValue", value);
};
const onBlur = () => {
  nextTick(() => {
    if (`${props.modelValue}`.endsWith(".")) {
      emit("update:modelValue", `${props.modelValue}`.replace(/\.+$/, ""));
    }
  });
};
</script>

<style lang="scss" scoped>
.money-field {
  --van-cell-horizontal-padding: 0;
  --van-field-label-margin-right: var(--dx-gap-xs);

  border-bottom: 1px solid var(--dx-color-gray-mute);

  @each $size in xs, sm, md, lg, xl {
    &--#{$size} {
      font-size: var(--dx-price-size-#{$size});
    }
  }
}
</style>
